package net.valerijtimakov.homefinances.dao.storages.common.mysql;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import net.valerijtimakov.homefinances.dao.storages.finances.mysql.IMySqlProvider;
import net.valerijtimakov.homefinances.domain.common.DataItem;
import net.valerijtimakov.homefinances.domain.common.OwnedItem;
import net.valerijtimakov.homefinances.exceptions.AppExceptionWrongState;
import net.valerijtimakov.homefinances.exceptions.AppPersProviderException;

public abstract class OwnedItemsStorage extends ItemsStorage {
	
	public OwnedItemsStorage(IMySqlProvider provider) throws AppExceptionWrongState {
		super(provider);
	}

	protected String userIdFieldName = "owner_id";

	@Override
	protected <T extends DataItem> void parse(ResultSet rs, T item) throws SQLException {
		super.parse(rs, item);
		OwnedItem cItem = (OwnedItem)item;
		cItem.setUserId(rs.getLong(userIdFieldName));
	}
	
	@Override
	protected void initSelect() {
		super.initSelect();
		selectQuery.addField(userIdFieldName);
	}

	@Override
	protected <T extends DataItem> void addData(T item) {
		OwnedItem cItem = (OwnedItem)item;
		insertQuery.setFieldValue(userIdFieldName, cItem.getUserId());
	}

	@Override
	protected <T extends DataItem> void setUpdatedFields(T item) {
		OwnedItem cItem = (OwnedItem)item;
		updateQuery.setFieldValue(userIdFieldName, cItem.getUserId());
	}

	protected <T extends DataItem> Map<Long, T> getAllUserItems(long userId) 
		throws AppPersProviderException, AppExceptionWrongState 
	{
		initSelect();
		selectQuery.getWhere().setWhereCond("`" + userIdFieldName + "`=" + userId);
		return getMap();
	}
	
}
